from flask import g
from flask_restful import inputs
from flask_restful.reqparse import RequestParser
from flask_restful import Resource

from cache.article import ArticleDetailCache
from cache.user import UserHistoryCache
from toutiao.apps.home import constants
from toutiao.utils.decorators import loginrequired


class UserHistoryResourve(Resource):
    """
    浏览历史记录
    """
    method_decorators = [loginrequired]

    def get(self):

        # 1. 获取分页参数
        # positive: 正数
        qs_parser = RequestParser()
        qs_parser.add_argument('page', type=inputs.positive, required=False, location='args')
        qs_parser.add_argument('per_page', type=inputs.int_range(constants.DEFAULT_ARTICLE_PER_PAGE_MIN,
                                                                 constants.DEFAULT_ARTICLE_PER_PAGE_MAX,
                                                                 'per_page'),required=False, location='args')
        args = qs_parser.parse_args()
        page = 1 if args.page is None else args.page
        # args.per_page: 查询匹配项的总数
        per_page = args.per_page if args.per_page else constants.DEFAULT_ARTICLE_PER_PAGE_MIN

        # 2. 获取文章的id列表
        article_ids = UserHistoryCache(g.user_id).get_all()
        total_count = UserHistoryCache(g.user_id).get_total_count()
        # 3. 获取分页数据
        page_article_ids = article_ids[(page-1)*per_page:page*per_page]
        # 4. 遍历文章详详情
        results=[]
        for article_id in page_article_ids:
            article=ArticleDetailCache(article_id).get()
            # 课下作业:浏览记录中是否点赞在此加判断

            results.append(article)
        # 5.返回数据
        return {'total_count':total_count,'page':page,'per_page':per_page,'results':results}